import request from '@/utils/request'
import store from '@/store'
const user = {
	state: {
		userInfo: JSON.parse(localStorage.getItem('userInfo') == "" ? null : localStorage.getItem('userInfo')),
		token: localStorage.getItem('token') || '',
		InputBoxList:[],//当前菜单下的用户输入框配置
	},

	mutations: {
		SET_userInfo: (state, userInfo) => {
			state.userInfo = userInfo
		},
		SET_Toke: (state, token) => {
			state.token = token
		},
		REMOVE_token: (state, token) => {
			state.token = token
		},
		set_InputBoxList: (state, InputBoxList) => {
			state.InputBoxList = InputBoxList
		},
	},

	actions: { //异步操作mutation
		// 登录
		set_Login_info({
			commit
		}, data) {
			localStorage.setItem('userInfo', JSON.stringify(data.userInfo));
			localStorage.setItem('token', data.token);
			commit('SET_userInfo', data.userInfo)
			commit('SET_Toke', data.token)
		},
		//清除 token
		resetToken({
			commit
		}) {
			return new Promise(resolve => {
				localStorage.removeItem('token')
				commit('REMOVE_token', '')
				resolve()
			})
		},
		
		//获取用户的权限菜单
		getInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				request.doGet(store.getters.api.GLOBAL_sys_permission_queryMenuList, {
					token: state.token
				}).then(res => {
					// let arr2=[{children:null,icon: "el-icon-s-shop",id: "1384777804146057218",isLeaf: false,leaf: false,menuType: 0,name: "主数据管理",parentId: null,sortNo: 2,url: "MasterDataManagement"},
					// {children:[{id: "1384780339976118274", name: "菜单管理", parentId: "1384780219004002306", isLeaf: true, icon: "el-icon-s-operation",url:"MenuManagement"}],icon: "el-icon-s-shop",id: "1384777804146057218",isLeaf: false,leaf: false,menuType: 0,name: "系统管理",parentId: null,sortNo: 2,url: "SystemManagement"}]
					let arr = filterBtn(res.result)
					console.log('过滤掉按钮的菜单',arr);
					resolve(arr)
				}).catch(error => {
					reject(error)
				})
			})
		},
		set_InputBoxList({commit}, InputBoxList){
			commit('set_InputBoxList', InputBoxList)
		},
	}
}
//过滤出按钮类型
function filterBtn(routers) {
	let res=[]
	routers.forEach((item, index) => {
		if (item.menuType!=2) {
			if(item.children&&item.children.length>0){
				item.children=filterBtn(item.children)
			}
			if(item.children&&item.children.length==0){
				delete item.children
			}
			res.push(item);
		}
	})
	return res
}


export default {
	namespaced: true,
	...user
}
